#pragma once
#include <sys/epoll.h>
#include <string.h>
#include "Log.hpp"
#include "Error.hpp"


enum class EPOLL_TYPE
{
    LT,
    ET
};
class Epoll
{
public:
    Epoll(EPOLL_TYPE type = EPOLL_TYPE::LT)
    :_type(type)
    {}


    void EpollCreate()
    {
        _epollfd = epoll_create(_epollsz);
        if(_epollfd < 0)
        {
            LOG(ERROR,"EpollCreate failed %d-%s",errno,strerror(errno));
        }
    }
    EPOLL_TYPE EpollType()
    {
        return _type;
    }
    void EpollCtl(int fd, int op, uint32_t evt)
    {
        struct epoll_event event;
        event.events = evt; 
        if(_type == EPOLL_TYPE::ET)
            event.events |= EPOLLET; 
        event.data.fd = fd;
        cout << "EpollCtl fd = " << fd << endl;
        int n = epoll_ctl(_epollfd, op, fd, &event);
        if( n < 0)
        {
            LOG(ERROR,"EpollCtl failed %d-%s",errno,strerror(errno));
        }
    }
    int EpollWait(struct epoll_event *events,int timeout)
    {
        int n = epoll_wait(_epollfd,events,_maxevts,timeout);
        if(n < 0)
        {
            LOG(ERROR,"EpollWait failed %d-%s",errno,strerror(errno));
        }
        return n;
    }
    void EpollClose()
    {
        close(_epollfd);
    }

private:
    EPOLL_TYPE _type;
    int _epollfd;
    int _epollsz = 2;
    int _maxevts = 3;
};